package com.motong.gongdan.controller.system;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.util.IoUtils;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.motong.gongdan.config.CustomCellWriteHandler;
import com.motong.gongdan.config.ResponseData;
import com.motong.gongdan.config.auth.UserLoginToken;
import com.motong.gongdan.constant.CommonConstant;
import com.motong.gongdan.entity.*;
import com.motong.gongdan.enums.ObjectType;
import com.motong.gongdan.service.*;
import com.motong.gongdan.util.*;
import com.motong.gongdan.vo.ExcelModel.StockPrintListModel;
import com.motong.gongdan.vo.ExcelModel.StockPrintModel;
import com.motong.gongdan.vo.ExcelModel.StockPrintProductModel;
import com.motong.gongdan.vo.H5Vo.common.GroupCountVo;
import com.motong.gongdan.vo.H5Vo.common.ListTypeCountVo;
import com.motong.gongdan.vo.resp.StockDetailResp;
import com.motong.gongdan.vo.resp.StockInputResp;
import com.motong.gongdan.vo.system.CustomField.ColumnsConfigure;
import com.motong.gongdan.vo.system.CustomField.ColumnsConfigureList;
import com.motong.gongdan.vo.system.common.query.SecondGroupCondition;
import com.motong.gongdan.vo.system.otherVo.*;
import com.motong.gongdan.vo.system.stock.vo.StockBalanceVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author:fff
 * @time:2022/3/8
 */
@Api(value = "库存管理", tags = {"库存管理"})
@RestController
@RequestMapping(value = "/sys/stock/")
public class StockController {
    @Resource
    StockMsgService stockMsgService;
    @Resource
    ProductService productService;
    @Resource
    UserService userService;
    @Resource
    StockDetailService stockDetailService;
    @Resource
    UnitService unitService;
    @Resource
    CustomNumberService customNumberService;
    @Resource
    CustomFieldService customFieldService;
    @Resource
    MongoTemplate mongoTemplate;

    @Value("${excel.printTemplatePath}")
    private String printTemplatePath;


    @UserLoginToken
    @ApiOperation(value = "出入库列表")
    @RequestMapping(value = "stock_list", method = RequestMethod.POST)
    public ResponseData stockList(@RequestBody StockInputListVo vo) {
        List<Integer> ids = new ArrayList<>();
        if (vo.getCustomFieldSearch() != null && !vo.getCustomFieldSearch().isEmpty()) {
            List<Object> list = MongoUtils.getSearchResult(vo.getCustomFieldSearch(), "stockMsg", customFieldService, mongoTemplate);
            if (!CollectionUtils.isEmpty(list)) {
                list.forEach(l -> {
                    StockMsg stockMsg = JSONObject.parseObject(JSON.toJSONString(l)).toJavaObject(StockMsg.class);
                    ids.add(stockMsg.getId());
                });
            } else {
                ids.add(0);
            }
        }
        List<String> typeOther = new ArrayList<>();
        if (StringUtil.isNotBlank(vo.getTypeOther())) {
            typeOther = Arrays.asList(vo.getTypeOther().split(","));
        }
        IPage<StockInputResp> data = stockMsgService.getBaseMapper().getList(new Page<StockInputResp>(vo.getPage(), vo.getLimit()),
                new QueryWrapper<StockInputResp>()
                        .like(StringUtil.isNotBlank(vo.getCode()), "sm.code", vo.getCode())
                        .in(!CollectionUtils.isEmpty(typeOther), "sm.type_other", typeOther)
                        .between(vo.getStartTime() != null && vo.getEndTime() != null, "sm.time", vo.getStartTime(), vo.getEndTime())
                        .like(StringUtil.isNotBlank(vo.getComment()), "sm.comment", vo.getComment()).eq("sm.type", vo.getType())
                        .in(!CollectionUtils.isEmpty(ids), "sm.id", ids));
        if (!CollectionUtils.isEmpty(data.getRecords())) {
            data.getRecords().forEach(d -> {
                if (StringUtil.isNotBlank(d.getOther())) {
                    d.setCustomFieldVos(customFieldService.handleCustomFieldForList(d.getOther()));
                }
            });
        }
        return ResponseData.success(data);
    }


    @UserLoginToken
    @ApiOperation(value = "出入库单操作")
    @PostMapping(value = "stock_handle")
    public ResponseData<?> stockHandle(@RequestBody StockHandleVo vo) {
        StockMsg stockMsg = new StockMsg();
        BeanUtil.copyProperties(vo, stockMsg, true);
        boolean isUpdate = Objects.nonNull(vo.getId());
        if (!isUpdate) {
            if (StringUtil.isBlank(vo.getCode())) {
                String code = customNumberService.generator(vo.getType() == 0 ? 5 : 6);
                if ("fail".equals(code)) {
                    return ResponseData.fail(500, "流水号已用完，请手动输入");
                }
                stockMsg.setCode(code);
            }
            stockMsg.setCreateId(LoginUtil.getLoginUserId()).setCreateTime(new Date());
        }
        stockMsg.setUpdateTime(new Date());
        if (!CollectionUtils.isEmpty(stockMsg.getCustomFieldVos())) {
            stockMsg.setOther(customFieldService.handleObjectCreateOrEdit(stockMsg.getCustomFieldVos()).toJSONString());
        }
        stockMsgService.saveOrUpdate(stockMsg);
        if (StringUtil.isNotBlank(stockMsg.getOther())) {
            StockMsg newStockMsg = new StockMsg().setId(vo.getId()).setCode(vo.getCode()).setCustomFieldMess(JSONArray.parseArray(vo.getOther()));
            mongoTemplate.save(stockMsg);
        }
        if (!CollectionUtils.isEmpty(vo.getStockDetails())) {
            //清空所有库存详情
            stockDetailService.remove(new LambdaQueryWrapper<StockDetail>().eq(StockDetail::getSmId, vo.getId()));
            vo.getStockDetails().forEach(f -> {
                Product p = productService.getById(f.getProductId());
                if (vo.getType() == 0) {
                    p.setStock(p.getStock().add(f.getHandleNum()));
                } else {
                    p.setStock(p.getStock().subtract(f.getHandleNum()));
                }

                f.setCreateId(LoginUtil.getLoginUserId());
                f.setSmId(stockMsg.getId());
                f.setCreateTime(new Date());
                f.setUpdateTime(new Date());
                if (!CollectionUtils.isEmpty(f.getCustomFieldVos())) {
                    f.setOther(customFieldService.handleObjectCreateOrEdit(f.getCustomFieldVos()).toJSONString());
                }
                stockDetailService.saveOrUpdate(f);
                if (StringUtil.isNotBlank(f.getOther())) {
                    StockDetail stockDetail = new StockDetail();
                    stockDetail.setId(f.getId());
                    stockDetail.setCustomFieldMess(JSONArray.parseArray(f.getOther()));
                    mongoTemplate.save(stockDetail);
                }
                productService.saveOrUpdate(p);
            });
        }
        return ResponseData.success("success");
    }

    @UserLoginToken
    @ApiOperation(value = "出入库数据详情")
    @RequestMapping(value = "stock_detail", method = RequestMethod.POST)
    public ResponseData stockDetail(@RequestBody IdVo vo) {
        StockMsg sm = stockMsgService.getById(vo.getId());
        getStockDetail(sm);
        if (StringUtil.isNotBlank(sm.getOther())) {
            sm.setCustomFieldVos(customFieldService.handleCustomFieldForList(sm.getOther()));
        }
        return ResponseData.success(sm);
    }


    @UserLoginToken
    @ApiOperation(value = "编辑详情内删除明细")
    @RequestMapping(value = "detail_del", method = RequestMethod.POST)
    public ResponseData detailDel(@RequestBody IdVo vo) {
        StockDetail sd = stockDetailService.getById(vo.getId());
        StockMsg sm = stockMsgService.getById(sd.getSmId());
        List<StockDetail> list = stockDetailService.list(new QueryWrapper<StockDetail>().eq("sm_id", sm.getId()));
        if (!CollectionUtils.isEmpty(list) && list.size() <= 1) {
            return ResponseData.fail(500, "不可少于一条数据");
        } else {
            if (sm != null) {
                handleProductNowNum(sm, sd);
                stockDetailService.removeById(sd.getId());
                MongoUtils.deleteById(sd.getId(), mongoTemplate, "stockDetail");
                return ResponseData.success("success");
            }
        }
        return ResponseData.fail(500, "数据错误");
    }

    @UserLoginToken
    @ApiOperation(value = "出入库删除")
    @RequestMapping(value = "stock_del", method = RequestMethod.POST)
    public ResponseData stockDel(@RequestBody IdVo vo) {
        StockMsg sm = stockMsgService.getById(vo.getId());
        List<StockDetail> list = stockDetailService.list(new QueryWrapper<StockDetail>().eq("sm_id", sm.getId()));
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(l -> {
                handleProductNowNum(sm, l);
                stockDetailService.removeById(l.getId());
            });
        }
        stockMsgService.removeById(sm.getId());
        MongoUtils.deleteById(sm.getId(), mongoTemplate, "stockMsg");
        return ResponseData.success("success");
    }

    private void handleProductNowNum(StockMsg sm, StockDetail l) {
        Product p = productService.getById(l.getProductId());
        if (p != null) {
            if (sm.getType() == 0) {
                p.setStock(p.getStock().subtract(l.getHandleNum()));
            } else {
                p.setStock(p.getStock().add(l.getHandleNum()));
            }
            p.setUpdateTime(new Date());
            productService.updateById(p);
        }
    }


    @UserLoginToken
    @ApiOperation(value = "库存收发明细")
    @RequestMapping(value = "stock_msg", method = RequestMethod.POST)
    public ResponseData stockMsg(@RequestBody StockMsgVo vo) {
        IPage<StockDetailResp> data = stockMsgService.getBaseMapper().getStockDetail(new Page(vo.getPage(), vo.getLimit()),
                new QueryWrapper<StockDetailResp>()
                        .like(StringUtil.isNotBlank(vo.getProductCode()), "p.code", vo.getProductCode())
                        .like(StringUtil.isNotBlank(vo.getProductName()), "p.name", vo.getProductName())
                        .like(StringUtil.isNotBlank(vo.getProductSpecification()), "p.specification", vo.getProductSpecification())
                        .in(!CollectionUtils.isEmpty(vo.getType()), "sm.type", vo.getType())
                        .like(StringUtil.isNotBlank(vo.getCode()), "sm.code", vo.getCode())
                        .in(!CollectionUtils.isEmpty(vo.getTypeOther()), "sm.type_other", vo.getTypeOther())
                        .between(vo.getStartTime() != null && vo.getEndTime() != null, "sd.create_time", vo.getStartTime(), vo.getEndTime())
                        .like(StringUtil.isNotBlank(vo.getComment()), "sm.comment", vo.getComment()));
        if (!CollectionUtils.isEmpty(data.getRecords())) {
            JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(data.getRecords()));
            RedisUtil.set("excel:data:stockMsg:" + LoginUtil.getLoginUserId(), jsonArray);
            data.getRecords().forEach(d -> {
                List<CustomFieldVo> vos = new ArrayList<>();
                if (StringUtil.isNotBlank(d.getOther())) {
                    vos.addAll(customFieldService.handleCustomFieldForList(d.getOther()));
                }
                StockMsg stockMsg = stockMsgService.getById(d.getSmId());
                if (stockMsg != null && StringUtil.isNotBlank(stockMsg.getOther())) {
                    vos.addAll(customFieldService.handleCustomFieldForList(stockMsg.getOther()));
                }
                if (!CollectionUtils.isEmpty(vos)) {
                    d.setCustomFieldVos(vos);
                }
                if ("出库单".equals(d.getType())) {
                    d.setChangeNum(-Optional.ofNullable(d.getChangeNum()).orElse(0));
                }
            });
        }
        return ResponseData.success(data);
    }

    @UserLoginToken
    @ApiOperation(value = "库存收发明细导出")
    @RequestMapping(value = "stock_msg_export", method = RequestMethod.GET)
    public void stockMsgExport(HttpServletResponse response) throws IOException {
        JSONArray jsonArray = (JSONArray) RedisUtil.get("excel:data:stockMsg:" + LoginUtil.getLoginUserId());
        List<StockDetailResp> dataList = jsonArray.toJavaList(StockDetailResp.class);
        if (!CollectionUtils.isEmpty(dataList)) {
            AtomicInteger index = new AtomicInteger(1);
            dataList.forEach(d -> {
                d.setId(index.getAndIncrement());
            });
            String fileName = "exportExcel" + System.currentTimeMillis() + ".xlsx";
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
            EasyExcel.write(response.getOutputStream()).registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).sheet("库存明细导出数据").head(StockDetailResp.class).doWrite(dataList);
        }
    }


    @UserLoginToken
    @ApiOperation(value = "明细模版打印")
    @RequestMapping(value = "print", method = RequestMethod.GET)
    public void print(HttpServletResponse response, String ids, Integer flag) throws IOException, InvalidFormatException {

        String templateFileName;
        String newFileName;
        if (flag == 0) {
//             templateFileName = "/Users/fff/Downloads/print/入库单明细.xlsx";
//            newFileName = "/Users/fff/Downloads/print/" + "入库" + System.currentTimeMillis() + ".xlsx";
            templateFileName =  printTemplatePath.concat("入库单明细.xlsx");
            newFileName = "/service/excel/print/" + "入库" + System.currentTimeMillis() + ".xlsx";
//            templateFileName = "C:\\Users\\91045\\Desktop\\入库单明细.xlsx";
//            newFileName = "C:\\Users\\91045\\Desktop\\" + "入库" + System.currentTimeMillis() + ".xlsx";
        } else {
//            newFileName = "/Users/fff/Downloads/print/" + "入库" + System.currentTimeMillis() + ".xlsx";
//             templateFileName = "/Users/fff/Downloads/print/出库单明细.xlsx";
//            templateFileName = "C:\\Users\\91045\\Desktop\\出库单明细.xlsx";
//            newFileName = "C:\\Users\\91045\\Desktop\\" + "出库" + System.currentTimeMillis() + ".xlsx";
            templateFileName = printTemplatePath.concat("出库单明细.xlsx");
            newFileName = "/service/excel/print/" + "出库" + System.currentTimeMillis() + ".xlsx";
        }
//        String fileName = "/Users/fff/Downloads/print/" + "simpleFill" + System.currentTimeMillis() + ".xlsx";
        String fileName = "/service/excel/print/" + "simpleFill" + System.currentTimeMillis() + ".xlsx";
        File templateFile = new File(templateFileName);
        FileInputStream fis = new FileInputStream(templateFile);
        XSSFWorkbook workbook = new XSSFWorkbook(fis);
        List<String> idsList = Arrays.asList(ids.split(","));
        for (int i = 0; i < idsList.size() - 1; i++) {
            workbook.cloneSheet(0);
        }
        FileOutputStream out = new FileOutputStream(new File(fileName));
        out.flush();
        workbook.write(out);
        out.close();
        ExcelWriter excelWriter = EasyExcel.write(newFileName).withTemplate(fileName).build();

        for (int i = 0; i < idsList.size(); i++) {
            StockMsg sm = stockMsgService.getById(Integer.valueOf(idsList.get(i)));
            getStockDetail(sm);
            WriteSheet writeSheet = EasyExcel.writerSheet().build();
            writeSheet.setSheetNo(i);
            if (flag == 0) {
                writeSheet.setSheetName("入库单明细" + (i + 1));
            } else {
                writeSheet.setSheetName("出库单明细" + (i + 1));
            }
            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
            StockPrintModel sp = new StockPrintModel();
            sp.setStockCode(sm.getCode());
            sp.setType(sm.getTypeOther());
            sp.setCreateTime(sm.getCreateTime());
            sp.setComment(sm.getComment());
            User u = userService.getById(LoginUtil.getLoginUserId());
            sp.setHandleName(u.getName());
//            sp.setHandleName("fff");
            sp.setHandleTime(new Date());
            excelWriter.fill(sp, writeSheet);

            List<StockPrintProductModel> list = new ArrayList<>();
            if (!CollectionUtils.isEmpty(sm.getProductList())) {
                sm.getProductList().forEach(s -> {
                    StockPrintProductModel spp = new StockPrintProductModel();
                    SpringUtil.copyPropertiesIgnoreNull(s, spp);
                    spp.setStockNum(s.getHandleNum());
                    spp.setHandleNum(s.getHandleNum());
                    list.add(spp);
                });
                excelWriter.fill(list, fillConfig, writeSheet);
            }

        }

        Workbook sourceWorkbook = excelWriter.writeContext().writeWorkbookHolder().getWorkbook();
        Workbook targeWorkbook = new SXSSFWorkbook();
        Workbook workbook1 = mergeWorkSheet(targeWorkbook, sourceWorkbook, idsList.size(), flag);
        excelWriter.writeContext().writeWorkbookHolder().setWorkbook(workbook1);

        excelWriter.finish();
        File file = new File(newFileName);
        OwnUtil.fileToResponse(file, response);
        file.delete();
    }


    public Workbook mergeWorkSheet(Workbook targetWorkbook, Workbook sourceWorkbook, int size, int flag) {
        try {
            //表合并后新表名称
            Sheet targetSheet;
            if (flag == 0) {
                targetSheet = targetWorkbook.createSheet("入库单明细");
            } else {
                targetSheet = targetWorkbook.createSheet("出库单明细");
            }
            int secondSourceSheetLen = 0;
            SXSSFWorkbook sw = (SXSSFWorkbook) sourceWorkbook;
            for (int i = 0; i < size; i++) {
                XSSFSheet sheetAt1 = sw.getXSSFWorkbook().getSheetAt(i);
                POIUtil.copySheet(targetSheet, sheetAt1, targetWorkbook, sourceWorkbook, secondSourceSheetLen);
                secondSourceSheetLen += sheetAt1.getPhysicalNumberOfRows();
            }
            return targetWorkbook;
        } catch (Exception e) {
            return null;
        }
    }


    private void getStockDetail(StockMsg sm) {
        List<StockDetail> list = stockDetailService.list(new QueryWrapper<StockDetail>().eq("sm_id", sm.getId()));
        if (!CollectionUtils.isEmpty(list)) {
            List<StockProductVo> productList = new ArrayList<>();
            list.forEach(l -> {
                Product p = productService.getById(l.getProductId());
                Unit unit = unitService.getById(p.getUnitId());
                StockProductVo sp = new StockProductVo();
                sp.setId(l.getId());
                sp.setProductId(l.getProductId());
                sp.setHandleNum(l.getHandleNum());
                sp.setProductName(p.getName());
                sp.setProductCode(p.getCode());
                sp.setProductSpecification(p.getSpecification());
                sp.setUnit(unit.getName());
                sp.setMinimum(p.getMinimum());
                sp.setMaximum(p.getMaximum());
                sp.setSafe(p.getSafe());
                sp.setNowNum(p.getStock());
                sp.setUnitPrice(p.getUnitPrice());
                sp.setTotalPrice(p.getUnitPrice().multiply(sp.getHandleNum()).setScale(2, RoundingMode.DOWN));
                if (StringUtil.isNotBlank(l.getOther())) {
                    sm.setCustomFieldVos(customFieldService.handleCustomFieldForList(l.getOther()));
                }
                if (StringUtils.hasLength(l.getOther())) {
                    sp.setCustomFieldVos(new ArrayList<>());
                    cn.hutool.json.JSONArray array = JSONUtil.parseArray(l.getOther());
                    array.forEach(i -> sp.getCustomFieldVos().add(JSONUtil.toBean(JSONUtil.parseObj(i), CustomFieldVo.class)));
                    sp.getCustomFieldVos().forEach(i -> i.setCustomFieldMess(customFieldService.getById(i.getCustomFieldId())));
                }
                productList.add(sp);
            });
            sm.setProductList(productList);
        }
    }


    @UserLoginToken
    @ApiOperation(value = "列表模板打印")
    @RequestMapping(value = "listPrint", method = RequestMethod.GET)
    public void listPrint(HttpServletResponse response, String ids, Integer flag) throws IOException {
        String templateFileName;
        if (flag == 0) {
//             templateFileName = "/Users/fff/Downloads/入库单列表.xlsx";
            templateFileName =  printTemplatePath.concat("入库单列表.xlsx");
        } else {
//             templateFileName = "/Users/fff/Downloads/出库单列表.xlsx";
            templateFileName =  printTemplatePath.concat("出库单列表.xlsx");
        }
//        String fileName = "/Users/fff/Downloads/" + "simpleFill" + System.currentTimeMillis() + ".xlsx";
        String fileName = "/service/excel/print/" + "出入库单列表打印" + System.currentTimeMillis() + ".xlsx";
//        ExcelWriter excelWriter = EasyExcel.write(fileName).registerWriteHandler(new CustomCellWriteHandler()).withTemplate(templateFileName).build();
        CustomCellWriteHandler customCellWriteHandler = new CustomCellWriteHandler().setMiniColumnWidth(10).setCuMaxDateWidth(30);
        ExcelWriter excelWriter = EasyExcel.write(fileName).withTemplate(templateFileName).registerWriteHandler(customCellWriteHandler).build();
        WriteSheet writeSheet = EasyExcel.writerSheet().registerWriteHandler(customCellWriteHandler).build();
        FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
        List<StockPrintListModel> modelList = new ArrayList<>();
        int a = 0;
        for (String id : Arrays.asList(ids.split(","))) {
            a++;
            StockMsg sm = stockMsgService.getById(Integer.valueOf(id));
            getStockDetail(sm);
            StockPrintListModel stockPrintListModel = new StockPrintListModel();
            stockPrintListModel.setId(a);
            stockPrintListModel.setStockCode(sm.getCode());
            stockPrintListModel.setType(sm.getTypeOther());
            stockPrintListModel.setAddTime(sm.getTime());
            stockPrintListModel.setComment(sm.getComment());
            stockPrintListModel.setCreateTime(sm.getCreateTime());
            Integer createId = sm.getCreateId();
            User user = userService.getById(createId);
            stockPrintListModel.setCreateUser(user.getName());
            stockPrintListModel.setUpdateTime(sm.getUpdateTime());
            modelList.add(stockPrintListModel);
        }
        excelWriter.fill(modelList, fillConfig, writeSheet);
        StockPrintListModel sp = new StockPrintListModel();
        User loginUser = userService.getById(LoginUtil.getLoginUserId());
        sp.setHandleName(loginUser.getName());
        sp.setHandleTime(new Date());
        excelWriter.fill(sp, writeSheet);
        excelWriter.finish();
        File newFile = new File(fileName);
        OwnUtil.fileToResponse(newFile, response);
        newFile.delete();
    }


    @UserLoginToken
    @ApiOperation(value = "库存余额")
    @PostMapping(value = "stock_balance")
    public ResponseData<?> stockBalance(@RequestBody StockBalanceVo vo) {
        if (vo.getTypeOther() != null && vo.getTypeOther() == -1) {
            vo.setAttribute(3);
        }
        //第一次自定义搜索条件
        if (!CollectionUtils.isEmpty(vo.getCustomFieldMap())) {
            List<Integer> includeIds = customFieldService.searchCustomField(vo.getCustomFieldMap(), ObjectType.product.getCode());
            vo.setIds(CollectionUtils.isEmpty(includeIds) ? Collections.singletonList(0) : includeIds);
        }
        //第二次自定义筛选
        StockBalanceVo secondCondition = Optional.ofNullable(vo.getSearchOther()).orElse(new JSONObject()).toJavaObject(StockBalanceVo.class);
        if (!CollectionUtils.isEmpty(secondCondition.getCustomFieldMap())) {
            List<Integer> otherIds = customFieldService.searchCustomField(secondCondition.getCustomFieldMap(), ObjectType.product.getCode());
            secondCondition.setIds(CollectionUtils.isEmpty(otherIds) ? Collections.singletonList(0) : otherIds);
        }

        // 二级分组查询条件
        if (Objects.nonNull(vo.getSecondSearchCondition()) && Objects.nonNull(vo.getSecondSearchCondition().getConditionName())) {
            SecondGroupCondition groupCondition = vo.getSecondSearchCondition();
            if ("attribute".equals(groupCondition.getConditionName())) {
                Integer integerValue = Integer.valueOf(groupCondition.getConditionValue());
                Integer attribute = vo.getAttribute();
                vo.setAttribute(Objects.isNull(attribute) || integerValue.equals(attribute) ? integerValue : -1);
            } else {
                List<Integer> includeIds = customFieldService.searchCustomField(Collections.singletonMap(Integer.valueOf(groupCondition.getConditionName()), groupCondition.getConditionValue()), ObjectType.product.getCode());
                if (CollectionUtils.isEmpty(includeIds)) {
                    vo.setIds(Collections.singletonList(0));
                } else {
                    if (CollectionUtils.isEmpty(vo.getIds())) {
                        vo.setIds(includeIds);
                    } else {
                        List<Integer> intersection = (List<Integer>) CollectionUtil.intersection(vo.getIds(), includeIds);
                        vo.setIds(CollectionUtils.isEmpty(intersection) ? Collections.singletonList(0) : intersection);
                    }
                }
            }
        }
        // 冲突条件合并
        Map<String, String> mergeRule = CommonConstant.STOCK_BALANCE_CONDITION_MERGE_RULE;
        StockBalanceVo mergeSearchResult = Optional.ofNullable(BeanMergeUtil.merge(mergeRule, vo, secondCondition, StockBalanceVo.class)).orElse(new StockBalanceVo());
        Page<Product> data = productService.getStockBalancePC(new Page<>(vo.getPage(), vo.getLimit()), mergeSearchResult);
        // 获取看板二级分组按类型获取数据条数
        List<GroupCountVo> typeCountData = productService.getSecondGroupTypeCount(vo.getScreenPlanId(), mergeSearchResult);
        ListTypeCountVo<Product> finalData = new ListTypeCountVo<>(typeCountData, data);
        finalData.setSecondGroupColumnName(mergeSearchResult.getSecondGroupColumnName());
        return ResponseData.success(finalData);
    }


    @UserLoginToken
    @ApiOperation(value = "出入库单内导入数据")
    @RequestMapping(value = "import_product", method = RequestMethod.POST)
    public ResponseData importProduct(MultipartFile file) throws IOException {
        byte[] stream = IoUtils.toByteArray(file.getInputStream());
        List<Map<String, String>> allDataList = EasyExcelImportUtils.parseExcelToData(stream, 2);

        ResponseData responseData = new ResponseData();
        //表格为空直接返回
        if (Objects.isNull(allDataList)) {
            responseData.setMessage("成功0条,失败0条。");
            responseData.setCode(200);
            responseData.setData(null);
            responseData.setMore(false);
            return responseData;
        }

        List<ColumnsConfigureList> allList = userService.handleDefault();
        int a = 0;
        int b = 0;

        String mess = "";
        List<ColumnsConfigure> defaultColumns = customFieldService.handleImportDefault("stockMsg");
        if (allList.stream().filter(f -> f.getType().equals("stockMsg")).findAny().orElse(null) != null) {
            List<Product> products = new ArrayList<>();
            List<ColumnsConfigure> list = allList.stream().filter(f -> f.getType().equals("stockMsg")).findAny().orElse(null).getColumns();
            for (Map<String, String> s : allDataList) {
                List<CustomFieldVo> vos = new ArrayList<>();
                //表头
                List<String> keyList = new ArrayList<>(s.keySet());
                if (!defaultColumns.stream().filter(f -> f.getChineseName().equals(keyList.get(0))).findAny().isPresent()) {
                    b++;
                    break;
                }
                int flag = 0;
                for (int i = 0; i < keyList.size() && flag == 0; i++) {
                    if (i >= list.size()) {
                        if (StringUtil.isNotBlank(keyList.get(i)) && StringUtil.isNotBlank(s.get(keyList.get(i)))) {
                            CustomField cf = customFieldService.getOne(new QueryWrapper<CustomField>().eq("field_ascription", "stockMsg").eq("chinese_name", keyList.get(i)));
                            CustomFieldVo vo = new CustomFieldVo();
                            vo.setCustomFieldId(cf.getId());
                            vo.setValue(s.get(keyList.get(i)));
                            vos.add(vo);
                        }
                    } else {
                        switch (i) {
                            case 0:
                                if (StringUtil.isNotBlank(s.get(keyList.get(i)))) {
                                    Product product = productService.getOne(new QueryWrapper<Product>().eq("code", s.get(keyList.get(i))));
                                    if (product == null) {
                                        b++;
                                        flag = 1;
                                        break;
                                    } else {
                                        products.add(product);
                                    }
                                } else {
                                    b++;
                                    flag = 1;
                                    break;
                                }
                                continue;
                            case 1:
                                if (StringUtil.isBlank(s.get(keyList.get(i)))) {
                                    b++;
                                    flag = 1;
                                    break;
                                }
                                continue;
                        }
                    }
                }
            }
            mess = "成功" + a + "条,失败" + b + "条。";
            responseData.setMessage(mess);
            responseData.setCode(200);
            responseData.setData(products);
            responseData.setMore(false);
        }
        return responseData;
    }


}
